from elasticsearch.helpers import bulk
from tqdm import tqdm

from src.base import Consts


class SyncFinanceIndicator:
    def __init__(self, logger, localDb, dataCenterDb, fcdb, es, enterpriseList):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb
        self.fcdb = fcdb
        self.es = es
        self.enterpriseList = enterpriseList

    def queryFinanceIndicator(self, creditCode):
        sql = """
            SELECT `year`,index_code,CONVERT(index_value,decimal(16.2)) as index_value,b.name  from fin_index  ri
            left join fin_index_calc_settings b on b.code=ri.index_code
            where ri.credit_code =%s and ri.index_code 
            in ('ZB_0302','ZB_0303','ZB_0505','ZB_0108','ZB_0116','ZB_0110','ZB_0306','ZB_0307')
            and `year` > 2020
        """
        query = self.localDb.Query(sql, (creditCode,))
        return query

    # 财务指标初始化
    def update(self):
        actions = []
        for item in tqdm(self.enterpriseList, desc="es数据库-财务指标保存/更新中...", position=0):
            creditCode = item['_source']['credit_code']
            entType = item['_source']['ent_type']
            if entType == 'T002':
                continue
            # qe级别下调
            body = {
                '_op_type': 'update',
                '_index': Consts.es_enterpriseList_index,
                "_id": item['_id'],
                "doc": {
                    "financeIndicator": self.queryFinanceIndicator(creditCode)
                }
            }
            actions.append(body)
            # self.es.update(index=Consts.es_enterpriseList_index, doc_type="test-type", id=, body=body)
        if actions:
            bulk(self.es, actions)
